# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import time
import cgitb
sys.excepthook = cgitb.Hook(1, None, 5, sys.stderr, 'text')

# 需要工作在子线程的程序继承的类必须是QObject
class Work(QObject):
    count = int(0)
    count_signal = pyqtSignal(int)

    def __init__(self, parent=None):
        super(Work, self).__init__(parent)
        self.run = True

    def work(self):
        print('current id', int(QThread.currentThreadId()))
        self.run = True
        while self.run:
            # print(str(self.count))
            self.count += 1
            self.count_signal.emit(self.count)
            time.sleep(1)

    def work_stop(self):
        self.run = False

class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.setup_ui()

        print('main id', int(QThread.currentThreadId()))

        self.thread = QThread()  # 这里设定的一个多线程是一个管理者
        self.worker = Work()  # 不能有父类
        self.worker.count_signal.connect(self.flush)

        self.worker.moveToThread(self.thread)  # 将耗时的类在设定的子线程中运行
        self.thread.finished.connect(self.finished)

    def setup_ui(self):
        self.setWindowTitle('movetothread')
        self.resize(500,500)

        self.btn1 = QPushButton('开始', self)
        self.btn1.resize(50,50)
        self.btn1.clicked.connect(self.workStart)

        self.btn2 = QPushButton('结束',self)
        self.btn2.resize(50, 50)
        self.btn2.move(0, 50)
        self.btn2.clicked.connect(self.workStop)

        self.label = QLabel(self)
        self.label.resize(100,100)
        self.label.move(100, 100)

    def flush(self, count):
        self.label.setText(str(count))

    def workStart(self):
        print('开始')
        self.btn1.setEnabled(False)
        self.thread.start()
        self.thread.started.connect(self.worker.work)  # 当子线程启动时，调用需要运行类的方法

    def workStop(self):
        print('结束')
        self.worker.work_stop()
        self.thread.quit()

    def finished(self):
        print('finish')
        self.btn1.setEnabled(True)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())